package org.sky.sys.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.Logger;
import org.sky.exception.ServiceException;
import org.sky.sys.entity.SysUser;
import org.sky.sys.entity.SysUserDataAccess;
import org.sky.sys.entity.SysUserRole;
import org.sky.sys.mapper.SysCommonMapper;
import org.sky.sys.mapper.SysUserDataAccessMapper;
import org.sky.sys.mapper.SysUserMapper;
import org.sky.sys.mapper.SysUserRoleMapper;
import org.sky.sys.util.BspUtils;
import org.sky.sys.util.page.PageListData;
import org.sky.sys.util.page.PageListDataUtils;
import org.sky.util.EncryptUtils;
import org.sky.util.LogUtils;
import org.sky.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author weifx
 * @Title: SysUserService
 * @ProjectName springboot-platform
 * @Description: TODO{用户信息业务类}
 * @date 2019/2/28 22:45
 * @Version 1.0
 */
@Service
public class SysUserService {
    private Logger log = LogUtils.getLogger(SysOrganService.class);
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysCommonMapper sysCommonMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserDataAccessMapper sysUserDataAccessMapper;
    /**
     * 根据用户编号获取用户信息
     * @param code
     * @return
     */
    public SysUser getSysUserByCode(String code){
        return sysUserMapper.selectOne(new SysUser().setCode(code));
    }

    /**
     * 根据主键查询用户
     * @param id
     * @return
     */
    public SysUser getSysUserById(Long id){
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("id",id);
        return sysUserMapper.selectOneByExample(example);
    }
    /**
     * 用户数据分页查询
     * @param pageNum
     * @param pageSize
     * @param example
     * @return
     */
    public PageListData selectSysUserByPage(int pageNum, int pageSize, Example example){
        PageHelper.startPage(pageNum, pageSize);
        final PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(sysUserMapper.selectFullFieldByExample(example));
        return PageListDataUtils.getPageListData().setTotal(pageInfo.getTotal()).setRows(pageInfo.getList());
    }
    /**
     * 保存{新增/修改}用户
     * @param sysUser
     */
    public void saveAddEditSysUser(SysUser sysUser){
        try{
            Timestamp ts = sysCommonMapper.queryTimestamp();
            if(null == sysUser.getId()){
                //新增
                sysUser.setId(SnowflakeIdWorker.getInstance().nextId());
                sysUser.setCreater(BspUtils.getLoginUser().getCode());
                sysUser.setCreateTime(ts);
                sysUser.setUpdater(BspUtils.getLoginUser().getCode());
                sysUser.setUpdateTime(ts);
                sysUser.setPassword(EncryptUtils.MD5Lower("111111"));
                sysUserMapper.insertSelective(sysUser);
            }else{
                //修改
                sysUser.setUpdater(BspUtils.getLoginUser().getCode());
                sysUser.setUpdateTime(ts);
                Example example = new Example(SysUser.class);
                example.createCriteria().andEqualTo("id",sysUser.getId());
                sysUserMapper.updateByExampleSelective(sysUser,example);
            }
        }catch(Exception e){
            log.error("用户保存失败:{}",e.getMessage());
            throw new ServiceException("用户保存失败:"+e.getMessage(),e);
        }
    }

    /**
     * 根据Id删除用户
     * @param delList
     */
    @Transactional
    public void delSysUserById(List<SysUser> delList) throws ServiceException{
        try {
            for (SysUser del : delList) {
                Example example = new Example(SysUser.class);
                example.createCriteria().andEqualTo("id", del.getId());
                sysUserMapper.deleteByExample(example);
                //删除用户角色及数据权限
                Example sure = new Example(SysUserRole.class);
                sure.createCriteria().andEqualTo("userCode", del.getCode());
                sysUserRoleMapper.deleteByExample(sure);
                Example sudae = new Example(SysUserDataAccess.class);
                sudae.createCriteria().andEqualTo("userCode", del.getCode());
                sysUserDataAccessMapper.deleteByExample(sudae);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户删除失败:{}",e.getMessage());
            throw new ServiceException("用户删除失败:"+e.getMessage(),e);
        }
    }

    /**
     * 密码重置
     * @param list
     * @throws ServiceException
     */
    @Transactional
    public void resetPwd(List<SysUser> list) throws ServiceException{
        try{
            for(SysUser su:list){
                SysUser user= new SysUser();
                user.setPassword(EncryptUtils.MD5Lower("111111"));
                user.setUpdateTime(sysCommonMapper.queryTimestamp());
                Example sue = new Example(SysUser.class);
                sue.createCriteria().andEqualTo("code",su.getCode());
                sysUserMapper.updateByExampleSelective(user,sue);
            }
        }catch(Exception e){
            log.error("密码重置失败:{}",e.getMessage());
            throw new ServiceException("密码重置失败:"+e.getMessage(),e);
        }
    }

    /**
     * 查询用户所具有的角色
     * @param pageNum
     * @param pageSize
     * @param example
     * @return
     */
    public PageListData selectSysUserRoleByPage(int pageNum, int pageSize, Example example){
        PageHelper.startPage(pageNum, pageSize);
        final PageInfo<SysUserRole> pageInfo = new PageInfo<SysUserRole>(sysUserRoleMapper.selectFullFieldByExample(example));
        return PageListDataUtils.getPageListData().setTotal(pageInfo.getTotal()).setRows(pageInfo.getList());
    }

    /**
     * 保存用户分配角色
     * @param addlist
     * @param updatelist
     * @throws ServiceException
     */
    @Transactional
    public void saveAddEditSysUserRoleList(List<SysUserRole> addlist,
                                List<SysUserRole> updatelist) throws ServiceException{
        try{
            Timestamp ts = sysCommonMapper.queryTimestamp();
            if(null!=addlist&&addlist.size()>0){
                for(SysUserRole add:addlist){
                    add.setId(SnowflakeIdWorker.getInstance().nextId());
                    add.setCreater(BspUtils.getLoginUser().getCode());
                    add.setCreateTime(ts);
                    add.setUpdater(BspUtils.getLoginUser().getCode());
                    add.setUpdateTime(ts);
                    sysUserRoleMapper.insertSelective(add);
                }
            }
            if(null!=updatelist&&updatelist.size()>0){
                for(SysUserRole update:updatelist){
                    update.setUpdater(BspUtils.getLoginUser().getCode());
                    update.setUpdateTime(ts);
                    sysUserRoleMapper.updateByPrimaryKeySelective(update);
                }
            }
        }catch(Exception e){
            log.error("用户分配角色出失败:{}",e.getMessage());
            throw new ServiceException("用户分配角色出失败:"+e.getMessage());
        }
    }

    /**
     * 删除用户角色
     * @param list
     */
    @Transactional
    public void delSysUserRole(List<SysUserRole> list) throws ServiceException{
        try {
            for (SysUserRole sur : list) {
                Example example = new Example(SysUserRole.class);
                example.createCriteria().andEqualTo("id", sur.getId());
                sysUserRoleMapper.deleteByExample(example);
            }
        }catch (Exception e){
            log.error("用户角色删除失败:{}",e.getMessage());
            e.printStackTrace();
            throw new ServiceException("用户角色删除失败:"+e.getMessage(),e);
        }
    }

    /**
     * 查询所有用户信息
     * @return
     */
    public List<SysUser> selectAll(){
        return sysUserMapper.selectAll();
    }

    /**
     * 批量插入
     * @param sysUserList
     */
    @Transactional
    public void batchInsert(List<SysUser> sysUserList){
        Timestamp ts = sysCommonMapper.queryTimestamp();
        for(SysUser sysUser:sysUserList) {
            sysUser.setId(SnowflakeIdWorker.getInstance().nextId());
            //sysUser.setCreater(BspUtils.getLoginUser().getCode());
            sysUser.setPassword(EncryptUtils.MD5Lower("111111"));
            sysUser.setCreateTime(ts);
            //sysUser.setUpdater(BspUtils.getLoginUser().getCode());
            sysUser.setUpdateTime(ts);
            sysUserMapper.insertSelective(sysUser);
        }
    }

    /**
     * 批量更新
     * @param sysUserList
     */
    @Transactional
    public void batchUpdate(List<SysUser> sysUserList){
        Timestamp ts = sysCommonMapper.queryTimestamp();
        for(SysUser su:sysUserList){
            su.setUpdateTime(ts);
            Example sue = new Example(SysUser.class);
            sue.createCriteria().andEqualTo("code",su.getCode());
            sysUserMapper.updateByExampleSelective(su,sue);
        }
    }

    /**
     * 批量插入用户角色
     * @param sysUserRoleList
     */
    @Transactional
    public void batchInsertUserRole(List<SysUserRole> sysUserRoleList){
        Timestamp ts = sysCommonMapper.queryTimestamp();
        for(SysUserRole sysUserRole:sysUserRoleList) {
            sysUserRole.setId(SnowflakeIdWorker.getInstance().nextId());
            //sysUser.setCreater(BspUtils.getLoginUser().getCode());
            sysUserRole.setCreateTime(ts);
            //sysUser.setUpdater(BspUtils.getLoginUser().getCode());
            sysUserRole.setUpdateTime(ts);
            sysUserRoleMapper.insertSelective(sysUserRole);
        }
    }
}
